﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using System.Windows.Markup;
using DeepEarth.Core.Utilities;

namespace DeepEarth.Core
{
    [ContentProperty("Children")]
    public class MultiCommand : ICommand
    {
        public ObservableCollection<ICommand> Children { get; set; }
       
        public MultiCommand(params ICommand[] commands) : this()
        {
            foreach (ICommand command in commands)
            {
                Children.Add(command);
            }
        }

        public MultiCommand()
        {
            Children = new ObservableCollection<ICommand>();
        }

        public bool CanExecute(object parameter)
        {
            return Children.All(c => c.CanExecute(parameter));
        }

        public event System.EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            Children.Iter(c => c.Execute(parameter));
        }

        public static MultiCommand Combine(ICommand existingCommand, ICommand newCommand)
        {
            var multiCommand = new MultiCommand();

            if (existingCommand != null)
            {
                if (existingCommand is MultiCommand)
                {
                    multiCommand = existingCommand as MultiCommand;
                }
                else
                {
                    multiCommand.Children.Add(existingCommand);
                }
            }
            else
            {
                if (newCommand is MultiCommand)
                {
                    multiCommand = newCommand as MultiCommand;
                }
            }

            if (multiCommand != newCommand && !multiCommand.Children.Contains(newCommand))
            {
                multiCommand.Children.Add(newCommand);
            }

            return multiCommand;
        }
    }
}